package com.yzc.mihuyou.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzc.mihuyou.entity.*;
import com.yzc.mihuyou.mapper.*;
import com.yzc.mihuyou.service.*;
import com.yzc.mihuyou.util.CommentUtils;
import com.yzc.mihuyou.util.MailClient;
import com.yzc.mihuyou.util.TokenProccessor;
import com.yzc.mihuyou.vo.JsonResult;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 登录注册
 * </p>
 *
 * @author 易紫诚
 * @since 2022-04-28
 */
@RestController
@RequestMapping("/mihuyou/user")
@CrossOrigin
public class UserController {
    @Autowired
    UserService service;

    @Autowired
    UserimgService userimgService;

    @Autowired
    MailClient mailClient;

    @Autowired
    InvitationMapper invitationMapper;

    @Autowired
    GiveMapper giveMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    IngvseService ingvseService;

    @Autowired
    TopicService topicService;

    @Autowired
    CompilationsMapper compilationsMapper;

    @Autowired
    IccompMapper iccompMapper;

    @Autowired
    PlateMapper plateMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    UserService userService;

    @Autowired
    PingiveService pingiveService;

    @PostMapping("/logion")
    public JsonResult login(@RequestPart("name") String name,@RequestPart("password") String password,HttpServletResponse response){
        System.out.println(name);
        System.out.println(password);
        Map<String,Object> hm = new HashMap<>();    // 通    过map返回token和user
        User user = service.LoginUser(name, password);    // Service类中的方法验证并获取用户
        if (user == null) {
            return new JsonResult(400,"账号或密码错误");
        }
        String token = TokenProccessor.getToken(user.getUserId()+"");
        //把user实体类转化成json格式
        String userJoin = JSON.toJSONString(user);
            //创建cookie
            Cookie cookie = new Cookie("id", token);
            response.addCookie(cookie);
            //把用户信息存入redis  set（key，value，过期时长，过期格式） 设置三天过期
            stringRedisTemplate.opsForValue().set(token, userJoin, 3, TimeUnit.DAYS);

        // 生成token并返回
        hm.put("token", token);
        user.setUserPassword("");
        String img=userimgService.selImage(user.getUserPortrait());
        user.setUserImage(img);
        hm.put("user", user);
        return new JsonResult(200,"登录成功",hm);

    }

    @PostMapping("/register")
        public  JsonResult register(User user){
        if(user.getUserPortrait()==null){
            user.setUserPortrait(0);
        }
        JsonResult ther=service.addUser(user);
        return ther;
    }

    @PostMapping("/upUser")
    public JsonResult upUser(User user){
        System.out.println(user);
        return service.upUser(user);
    }

    @PostMapping("ser")
    public JsonResult upUser(String urak){
        System.out.println(urak);
        Map<String,Object> map=new HashMap<>();
        String sa=mailClient.sendMail(urak, "短信验证码");
        map.put("Tory",sa);
        return new JsonResult(200,"发送成功", map);
    }


    @GetMapping("suePre/selIngv/{id}")
    public  JsonResult selIngv(@PathVariable("id") Long id, PageWuer pageWuer){
        Map<String,Object> map=new HashMap<>();
        if(pageWuer.getSize()==null){
            pageWuer.setSize(5L);
        }
        if(pageWuer.getCurrent()==null){
            pageWuer.setCurrent(0L);
        }
        Page<Invitation> page = new Page<>(new Long(pageWuer.getCurrent()), new Long(pageWuer.getSize()));
        QueryWrapper<Invitation> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("invitation_come",id);
        queryWrapper.orderByDesc("gmt_create");

       List<Invitation>invitationsList=invitationMapper.selectPage(page,queryWrapper).getRecords();
        List list = new ArrayList<>(); //获取发帖的用户信息
        for (int i = 0; i < invitationsList.size(); i++){
            Map<String, Object> map1 = new HashMap<>();
//           帖子
            map1.put("nvitations", invitationsList.get(i));
            Document doc = Jsoup.parse(invitationsList.get(i).getGmtContent());
            Elements element = doc.getElementsByTag("p");
            Elements element2 = doc.getElementsByTag("img");
            element2.attr("preview","imgPreview");
            List<String> listImgs=new ArrayList<>();
            for (int op=0;op<element2.size();op++){
                listImgs.add(op,element2.get(op).attr("src"));
            }
            map1.put("img",listImgs);
            map1.put("text",element.text());


            //        获取点赞的数量
            QueryWrapper queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("invitation_id", invitationsList.get(i).getInvitationId());
            queryWrapper2.eq("invtation_prin",1);
            invitationsList.get(i).setSums(giveMapper.selectCount(queryWrapper2));

            //获取关注的数量
            QueryWrapper queryWrapper3 = new QueryWrapper();
            queryWrapper3.eq("invitation_id", invitationsList.get(i).getInvitationId());
            queryWrapper3.eq("invtation_ore", 1);
            invitationsList.get(i).setZwu(giveMapper.selectCount(queryWrapper3));
//            获取帖子的话题
            Ingvse ingvse= ingvseService.selTope(invitationsList.get(i).getInvitationId());
            if(ingvse.getInvitionId()!=null && !ingvse.getTopicId().equals("")){
                List<String> ingvseList= CommentUtils.strUwe(ingvse.getTopicId());
                List<Topic> list1 = new ArrayList<>();
                for (int ik=0;ik<ingvseList.size();ik++){
                    if(!ingvseList.get(ik).equals("")){
                        list1.add(ik,topicService.selTope(Integer.parseInt(ingvseList.get(ik))));
                    }
                }
                map1.put("tope", list1);

            }else {
                map1.put("tope", null);
            }
//           获取评论数量
                QueryWrapper<Invitation> queryWrappery = new QueryWrapper<>();
                queryWrapper.eq("giv_we",0);
                queryWrapper.eq("blog_id", invitationsList.get(i).getInvitationId());
                invitationsList.get(i).setCommentNum(invitationMapper.rowesNun(queryWrappery).getCommentNum());

            if (id > 0) {
                QueryWrapper<Give> queryWrappers = new QueryWrapper<>();
                queryWrappers
                         .eq("invitation_id",invitationsList.get(i).getInvitationId())
                         .eq("give_userid", id);
                Give give = giveMapper.selectOne(queryWrappers);
                map1.put("igact", give);
            }
            list.add(i, map1);
        }
        map.put("InveArr", list);
        map.put("page",new PageWuer(page.getTotal(),page.getSize(),page.getCurrent(),page.getPages()));
        return new  JsonResult(200,"查询成功",map);
    }

        @GetMapping("suePre/comes/{id}")
    public  JsonResult comes(@PathVariable("id") Long id, PageWuer pageWuer){
        Map<String,Object> map=new HashMap<>();
        if(pageWuer.getSize()==null){
            pageWuer.setSize(5L);
        }
        if(pageWuer.getCurrent()==null){
            pageWuer.setCurrent(0L);
        }
        Page<Comment> page = new Page<>(new Long(pageWuer.getCurrent()), new Long(pageWuer.getSize()));
        QueryWrapper<Comment> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        queryWrapper.orderByDesc("gmt_create");
        List<Comment> commentList=commentMapper.selectPage(page,queryWrapper).getRecords();
        List list=new ArrayList();
        for (int q=0;q<commentList.size();q++){
            System.out.println(commentList.get(q).getRootParentId());
            Map<String,Object> map1=new HashMap<>();
            commentList.get(q).setUser(service.cuw(commentList.get(q).getUserId()));
            if(commentList.get(q).getParentId()==0 && commentList.get(q).getRootParentId()==0){
              Invitation invitation = invitationMapper.selectById(commentList.get(q).getBlogId());
              map1.put("dneg",invitation);
            }else {
                   Comment comment=commentMapper.selectById(commentList.get(q).getParentId());
                   map1.put("comen",comment);
            }
            map1.put("loa",commentList.get(q));
            list.add(list.size(),map1);
        }
        PageWuer pages=new PageWuer(page.getTotal(),page.getSize(),page.getCurrent(),page.getPages());
        map.put("ListPin",list);
        map.put("pages",pages);
        return new  JsonResult(200,"查询成功",map);
    }



    @GetMapping("suePre/compit/{id}")
    public  JsonResult selIngv(@PathVariable("id") Long id){
        Map<String,Object> map=new HashMap<>();
        QueryWrapper<Compilations> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        List<Compilations> CompilationsList= compilationsMapper.selectList(queryWrapper);

        for (int i=0;i<CompilationsList.size();i++){
            QueryWrapper queryWrapper1=new QueryWrapper();
            queryWrapper.eq("comments_id",CompilationsList.get(i).getId());
            CompilationsList.get(i).setNum(iccompMapper.selectCount(queryWrapper1));
        }
        map.put("compit", CompilationsList);
        return new  JsonResult(200,"查询成功",map);
    }

    @GetMapping("suePre/gives/{id}")
    public  JsonResult gives(@PathVariable("id") Long id,PageWuer pageWuer){
        Map<String,Object> map=new HashMap<>();
        QueryWrapper<Give> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("give_userid",id);
        queryWrapper.eq("invtation_ore",1);

        if(pageWuer.getSize()==null){
            pageWuer.setSize(5L);
        }
        if(pageWuer.getCurrent()==null){
            pageWuer.setCurrent(0L);
        }
        Page<Give> page = new Page<>(new Long(pageWuer.getCurrent()), new Long(pageWuer.getSize()));

        List<Give> compilationsList= giveMapper.selectPage(page,queryWrapper).getRecords();
        System.out.println(compilationsList.size());
        List list=new ArrayList();
        for (int i=0;i<compilationsList.size();i++){
           Invitation invitation= invitationMapper.selectById(compilationsList.get(i).getInvitationId());
            Map<String, Object> map1 = new HashMap<>();
            Document doc = Jsoup.parse(invitation.getGmtContent());
//           如果是首页的话就回去帖子的模块
            if(id==0){
                map1.put("plate",plateMapper.selectById(invitation.getGmtReprint()));
            }
            Elements element = doc.getElementsByTag("p");
            Elements element2 = doc.getElementsByTag("img");
            element2.attr("preview","imgPreview");
            List<String> listImgs=new ArrayList<>();
            for (int op=0;op<element2.size();op++){
                listImgs.add(op,element2.get(op).attr("src"));
            }
            map1.put("img",listImgs);
            map1.put("text",element.text());
//            创建帖子的用户
            map1.put("nvitationsUser", service.selUser(invitation.getInvitationCome()));
            //        获取点赞的数量
            QueryWrapper queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("invitation_id", invitation.getInvitationId());
            queryWrapper2.eq("invtation_prin",1);
            invitation.setSums(giveMapper.selectCount(queryWrapper2));
            //获取关注的数量
            QueryWrapper queryWrapper3 = new QueryWrapper();
            queryWrapper3.eq("invitation_id", invitation.getInvitationId());
            queryWrapper3.eq("invtation_ore", 1);
            invitation.setZwu(giveMapper.selectCount(queryWrapper3));
//            获取帖子的话题
            Ingvse ingvse= ingvseService.selTope(invitation.getInvitationId());
            if(ingvse.getInvitionId()!=null && !ingvse.getTopicId().equals("")){
                List<String> ingvseList= CommentUtils.strUwe(ingvse.getTopicId());
                List<Topic> list1 = new ArrayList<>();
                for (int ik=0;ik<ingvseList.size();ik++){
                    if(!ingvseList.get(ik).equals("")){
                        list1.add(ik,topicService.selTope(Integer.parseInt(ingvseList.get(ik))));
                    }
                }
                map1.put("tope", list1);
            }else {
                map1.put("tope", null);
            }
//           获取评论数量
            QueryWrapper<Invitation> queryWrappersr = new QueryWrapper<>();
            queryWrapper.eq("giv_we",0);
            queryWrapper.eq("blog_id", invitation.getInvitationId());
            invitation.setCommentNum(invitationMapper.rowesNun(queryWrappersr).getCommentNum());
//          是否收藏 是否点赞
            if (id > 0) {
                QueryWrapper<Give> queryWrappery = new QueryWrapper<>();
                queryWrappery
                        .eq("invitation_id", invitation.getInvitationId())
                        .eq("give_userid", id);
                Give give = giveMapper.selectOne(queryWrappery);
                map1.put("igact", give);
            }
            //  帖子
            map1.put("nvitations", invitation);
            list.add(i, map1);
        }

        map.put("compit", list);
        PageWuer pages=new PageWuer(page.getTotal(),page.getSize(),page.getCurrent(),page.getPages());
        map.put("pages",pages);
        return new  JsonResult(200,"查询成功",map);
    }

    @GetMapping("/getUser/{id}")
    public JsonResult getUser(@PathVariable("id") long id){
        return service.getUser(id);
    }

    @PostMapping("/likeUser")
    public JsonResult likeUser(String str,PageWuer pageWuer){
        System.out.println(str);
        if(pageWuer.getSize()==null){
            pageWuer.setSize(5L);
        }
        if(pageWuer.getCurrent()==null){
            pageWuer.setCurrent(0L);
        }
        return service.likeUser(str,pageWuer);
    }


    @DeleteMapping("dele")
    public  JsonResult dele(HttpServletRequest request){
        String token = request.getHeader("token");
        if(token!=null){
            new JsonResult(401,"退出异常");
        }
        System.out.println(token);
        stringRedisTemplate.delete(token);
        return new JsonResult(200,"退出成功");
    }

}

